package com.game.service.db;

import com.game.service.app.PostJson;
import com.game.service.app.Utils;
import com.game.service.beans.UserInfo;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.object.BatchSqlUpdate;

import javax.sql.DataSource;
import java.sql.Types;
import java.util.List;

import static com.game.service.define.RoomConfig.*;

public class UserScoreDaoImpl {
    private static UserScoreDaoImpl instance;
    private static JdbcTemplate jdbcTemplate;
    private static final String DB_URL = "jdbc:mysql://localhost:3306/arrow_db?useSSL=false&serverTimezone=UTC";
    private static final String DB_PWD = "qq123456";

    public static final String CHANGE_TYPE_LOGIN = "首次登录";
    public static final String CHANGE_TYPE_LOGIN_OFFLINE = "断线登录";
    public static final String CHANGE_TYPE_FEE = "参赛费";
    public static final String CHANGE_TYPE_WIN = "获得奖励";
    public static final String CHANGE_TYPE_EXIT = "主动退出";

    private UserScoreDaoImpl() {
    }

    public static UserScoreDaoImpl getInstance() {
        if (instance == null) {
            instance = new UserScoreDaoImpl();
            instance.init();
        }
        return instance;
    }

    private void init() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");//
        dataSource.setUrl(DB_URL);//
        dataSource.setUsername(DB_NAME);
        dataSource.setPassword(DB_PWD);
        jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);

    }

    /***
     *  玩家分数流水记录
     * @param info 变动信息
     */
    public void addUserScoreUpdate(UserScoreUpdate info) {
        String sql = "INSERT into `user_score_update` (uid,currentScore,changeType,location,score,changeScore,remark,createTime) VALUES(?,?,?,?,?,?,?,?);";
        Object[] obj = {info.getUid(), info.getCurrentScore(), info.getChangeType(), info.getLocation(), info.getScore(), info.getChangeScore(), info.getRemark(), Utils.getTime()};
        jdbcTemplate.update(sql, obj);
    }

    /***
     *  玩家分数实时记录
     * @param pid 玩家id
     * @param postJson 分数json
     * @param jsonDesc 最后状态
     */
    public void updateUserScore(String pid, String postJson, String jsonDesc) {
        String sql = "UPDATE `user_score` SET postResult=0,postJson=?,jsonDesc=? WHERE pid=?;";
        jdbcTemplate.update(sql, postJson, jsonDesc, pid);
    }

    /***
     * 玩家退出
     * @param pid 玩家id
     * @param jsonDesc 退出类型,1.主动结算,2.系统结算,3.解锁结算
     */
    public void  userExit(String pid, String jsonDesc) {
        String sql = "UPDATE `user_score` SET postResult=1,successTime=?,jsonDesc=? WHERE pid=? and postResult=0 ;";
        jdbcTemplate.update(sql, Utils.getTime(), jsonDesc, pid);
    }

    public void userExitBatch(List<UserInfo> userInfoList, String jsonDesc ){
        DataSource dataSource = jdbcTemplate.getDataSource();
        assert dataSource != null;
        BatchSqlUpdate bsu = new BatchSqlUpdate(dataSource, "UPDATE `user_score` SET postResult=1,successTime=?,jsonDesc=? WHERE pid=? and postResult=0 ;");
        bsu.setBatchSize(1000);
        bsu.setTypes(new int[]{Types.DATE, Types.VARCHAR,Types.VARCHAR});

        for (UserInfo user : userInfoList) {
            bsu.update(Utils.getTime(), jsonDesc, user.getUid());
        }
        bsu.flush();
    }


    /***
     * 新增玩家
     *
     * @param info 玩家信息
     */
    public void addUserScore(PostJson info) {
        String sql = "INSERT into `user_score` (pid,jsonDesc,postResult,addCurrentTimeMillis,postJson,postUrl,createTime) VALUES(?,?,?,?,?,?,?);";
        Object[] obj = {info.getPid(), info.getJsonDesc(), info.getPostResult(), info.getAddCurrentTimeMillis(), info.getPostJson(), info.getPostUrl(), Utils.getTime()};
        jdbcTemplate.update(sql, obj);
    }

    /***
     * 获取玩家
     *
     * @param pid 玩家id
     */
    public PostJson getUserScore(String pid) {
        try {
            String sql = "SELECT * FROM `user_score` WHERE pid=?;";
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(PostJson.class), pid);
        } catch (Exception e) {
            return null;
        }
    }

    /***
     * 发送总服务器的请求,保存
     * @param info 请求信息
     */

    public void addLog(PostJson info) {
        String sql = "INSERT into `post_json` (pid,gameid,jsonDesc,postResult,addCurrentTimeMillis,postJson,postUrl,createTime) VALUES(?,?,?,?,?,?,?,?);";
        Object[] obj = {info.getPid(),info.getGameid(), info.getJsonDesc(), info.getPostResult(), info.getAddCurrentTimeMillis(), info.getPostJson(), info.getPostUrl(), Utils.getTime()};
        jdbcTemplate.update(sql, obj);
    }

    /***
     * 发送总服务器的请求,
     */
    public void updateLog(String pid) {
        String sql = "UPDATE `post_json` SET postResult=1,successTime=? WHERE pid=? and postResult=0;";
        jdbcTemplate.update(sql, Utils.getTime(), pid);
    }

    /***
     * 加载未处理的请求，再次发送
     * @return 未发送成功的list
     */
    public List<PostJson> getList(int gameid) {
        String sql = "SELECT * FROM `post_json` WHERE  postResult=0 AND gameid=? LIMIT 100;";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(PostJson.class),gameid);
    }

}
